// mircoApp/shopsProfits/profitsPay/profitsPay.js
var yz_pay = require("../../../mycomponent/yz_pay/yz_pay");
var app = getApp();
Page({
  behaviors: [yz_pay],
  /**
   * 页面的初始数据
   */
  data: {
    isClick: 0,
    showPage: false,
    qrcode: "",
    showQR: false,
    show1: false,
    order: {},
    price: 0,
    clicktag: 0,

    // 订单数据
    datas: {},

    //支付
    order_ids: "",
    balance: 0,
    order_sn: "",
    money: "",
    buttons: [],
    pay_sn: "订单编号",
    order_pay_id: "",
    uid: "",
    payType: [],
    typename: "",
    payMuch: "0",

    title_text:"支付",
    // 折扣自定义字段
    goodsDeductions:[],
    language:'',
    query:{
      orders: [],
      member_coupon_ids:[],
      address:'',
      store_profit_price:'',
      store_profit_uid:'',
      store_profit_image:''
    },
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initData();
    let profits = JSON.parse(wx.getStorageSync("profits"));
    if(Object.keys(profits).length !==0 ) {
      this.data.query.store_profit_price = profits.price;
      this.data.query.store_profit_uid = Number(profits.uid);
      this.data.query.store_profit_image = profits.image;
      this.setData({
        show1:true,
        showPage:true
      })
    }
    this.goodsBuy();
  },
  closePop() {
    this.setData({
      show1:false
    })
    wx.navigateBack({
      delta: 1,
      fail: (res) => {
        // 防止跳转不了 尝试直接指向商家让利
        wx.reLaunch({
          url: '/mircoApp/shopsProfits/profits/profits',
        });
      }
    });
  },
  goodsBuy() { //预下单
    this.setData({
      isClick:1
    })
    this.data.query.orders = JSON.stringify(this._assembleDeduction());
    let urlStr = app.getNetAddresss("plugin.store-profit.frontend.goods-buy.index");
    app._postNetWork({
      url: urlStr,
      data:this.data.query,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.setViewData(res.data);
          this.btnListIndex(parseFloat(res.data?.total_price));
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  setViewData(data){ //处理数据格式
    let goodsDeductions = data.orders[0]?.order_deductions;
    if(Object.prototype.toString.call(goodsDeductions) === '[object Object]' ) { //判断是对象转化数组格式
      goodsDeductions = Object.values(data.orders[0]?.order_deductions)
    }
    let orders = [];
    orders.push({
      pre_id: data.orders[0].pre_id
    })
    this.setData({
      isClick:0,
      datas:data,
      order_data:data.orders,
      payMuch:data.orders[0]?.order_goods_price, //商品的价格
      totalPrice:  data.total_price,
      goodsDeductions: goodsDeductions,
      price:data.total_price, //商品的总价
      'query.orders': orders
    })
  },
  btnListIndex(price) {
    let btnQuery = {
      store_profit_price:price
    }
    let urlStr = app.getNetAddresss("plugin.store-profit.frontend.payment-list.index");
    app._postNetWork({
      url: urlStr,
      data:btnQuery,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          let payTypeData = res.data;
          let arr = {};
          arr.buttons = res.data;
          this.hanleIcon(arr);
          this.setData({
            payType: payTypeData,
            show1: true,
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  discountHandle(event) {
    let index = event.currentTarget.dataset.index;
    this.setData({ //开启让利插件爱心值折扣关闭不了，避免开关错误问题
      [`order_data[0].order_deductions[${index}].checked`]:event.detail
    })
    if (this.data.isClick === 0) {
      this.goodsBuy();
    }
  },
  _assembleDeduction() { //组合折扣的数据
    //修改提交的orders数据
    let deductions = [];
    let DeductionsData = [];
    let DeductionsId = [];
    let goodsDeductions = this.data.goodsDeductions;
    let newObj = {};
    DeductionsData = goodsDeductions.filter(item => {
      //筛选选中的爱心值，积分等等
      return item.checked === true;
    });
    DeductionsData.forEach(item => {
      //获取code值
      DeductionsId.push(item.code);
    });
    if(Array.isArray(this.data.query.orders)) {
      this.data.query.orders.push({
        deduction_ids: DeductionsId,
      });
      this.data.query.orders.forEach(item => {//如果有多个折扣遍历添加
        if (item) {
          newObj = { ...newObj, ...item };
        }
      });
    }
    if (Array.prototype.isPrototypeOf(this.data.query.orders) && this.data.query.orders.length !== 0) {
      //不是空数组的时候才添加对象
      deductions.push(newObj);
    }
    return deductions;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    let language = wx.getStorageSync("langIndex");
    this.setData({
      language: language.en
    });
  },
  initData() {
    this.setData({
      isClick:0,
      showQR:false,
      showPage:false
    })
  },
  fromChild(e){
    if(this.data.money=='0.00'|| e.detail.money == '0.00') {
      // 0元
      // this.sureBtn();
      this.submit('54');
    }else {
      let datas = e.detail.submitArr;
      this.submit(datas);
    }
  },
  //提交订单
  submit(btn) {
    let val = btn;
    let urlStr = app.getNetAddresss("plugin.store-profit.frontend.create.index");
    this.data.query.orders = JSON.stringify(this._assembleDeduction());
    if (this.data.clicktag == 0) {
      this.setData({
        clicktag: 1,
      });
      app._getNetWork({
        url: urlStr,
        data:this.data.query,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            this.setData({
              order_ids: res.data.order_ids,
            });
            this.getMultipleOrderInfo(val);
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
          }
          setTimeout(() => {
            this.setData({
              clicktag: 0,
            });
          }, 1000);
        },
        fail: function (res) {
          console.log(res);
        },
      });
    }
  },
  //多订单合并支付获取信息接口方法
  getMultipleOrderInfo(val) {
    let urlStr = app.getNetAddresss("order.merge-pay");
    urlStr += "&order_ids=" + this.data.order_ids;
    urlStr += "&pid=" + this.data.uid;
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            order_sn: res.data.order_pay.pay_sn,
            balance: res.data.member.credit2,
            money: res.data.order_pay.amount,
            uid: res.data.order_pay.uid,
            order_pay_id: res.data.order_pay.id,
            buttons: res.data.buttons,
            min_redirect_url: res.data.min_redirect_url,
          });
          try {
            wx.removeStorageSync('profits');
          } catch (e) {
            console.log(e);
          }
          this.handlePay(val, val.value);
        } else {
          wx.showModal({
            title: "提示",
            content: res.msg,
            success(res) {
              if (res.confirm) {
                wx.reLaunch({
                  url: "/packageG/index/index",
                });
                console.log("用户点击确定");
              } else if (res.cancel) {
                console.log("用户点击取消");
              }
            },
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})